
// 手写 setInterval

function mySetInterval(fn, delay) {
  let timer = null;
  let startTime = null;
  let lastTime = 0
  function interval() {
    startTime = Date.now();
    if (startTime - lastTime >= delay) {
      fn();
      lastTime = startTime;
      timer = setTimeout(interval, delay);
    }
  }
  interval();
  return ()=> clearTimeout(timer);
}


// let cancleTime = mySetInterval(()=>{
//     console.log('123')
// }, 300)

// setTimeout(()=>{
//     cancleTime()
// }, 1000)

const simulateSetInterval = (func, delay)=>{
    let timer = null;
    const interval = ()=>{
        timer = setTimeout(()=>{
            func()
            interval()
        }, delay);
    }
    interval();
    return ()=> clearTimeout(timer);
}


// 测试
// let destoryTime = simulateSetInterval(()=>{
//     console.log('456')
// }, 300)

// setTimeout(()=>{
//     destoryTime()
// }, 1000)



function mySetTimeout(fn, delay) {
    let timer = true;
    let startTime = new Date().getTime();
    let lastTime = new Date().getTime();
    function interval() {
      startTime = new Date().getTime();
      if(timer === false) {
        return;
      }
      if (startTime - lastTime >= delay) {
        fn();
        lastTime = startTime;
      }else {
        interval();
      }
    }
    interval();
    return ()=> timer === false;
  }

  let cancleMyTime = mySetTimeout(()=>{
    console.log('timeout')
  }, 3000)

  mySetTimeout(()=>{
    cancleMyTime()
}, 1000)